<template>
  <el-card class="category-container">
    <template #header>
      <div class="header">
        <el-button type="primary" :icon="Plus" @click="handleAdd">增加</el-button>
      </div>
    </template>
    <el-table :load="state.loading" ref="multipleTable" :data="state.tableData" tooltip-effect="dark"
      style="width: 100%">
      <el-table-column prop="brandId" label="品牌ID">
      </el-table-column>
      <el-table-column prop="brandUrl" label="品牌图片">
        <template #default="scope">
          <img :src="scope.row.brandUrl" style="width: 50px;" alt="">
        </template>
      </el-table-column>
      <el-table-column prop="brandName" label="品牌名称">
      </el-table-column>
      <el-table-column prop="brandOrd" label="排序">
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button type="primary" style="margin-right: 10px;" @click="handleEdit(scope.row.brandId)">修改</el-button>
          <el-dropdown size="small" :hide-on-click="false" :hide-timeout="500">
            <el-button type="primary">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <el-popconfirm title="确定删除吗？" confirmButtonText='确定' cancelButtonText='取消'
                    @confirm="handleDeleteOne(scope.row.brandId)">
                    <template #reference>
                      <a style="cursor: pointer">删除</a>
                    </template>
                  </el-popconfirm></el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!--总数超过一页，再展示分页器-->
    <el-pagination background layout="total,prev, pager, next,jumper" :page-sizes="[10, 20, 50, 100]"
      :total="state.total" :page-size="state.pageSize" :current-page="state.currentPage" @current-change="changePage" />
    <el-dialog :title="state.title" v-model="state.visible" width="500px">
      <el-form :model="state.form" :rules="state.rules" ref="formRef" label-width="100px">
        <el-form-item label="品牌图片" prop="brandUrl">
          <el-upload class="avatar-uploader" :action="state.uploadImgServer" accept="jpg,jpeg,png" :headers="{
            token: state.token
          }" :show-file-list="false" :before-upload="handleBeforeUpload" :on-success="handleUrlSuccess">
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="state.form.brandUrl"
              :src="state.form.brandUrl" class="avatar">
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="品牌名称" prop="brandName">
          <el-input type="text" v-model="state.form.brandName"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="brandOrd">
          <el-input type="number" v-model="state.form.brandOrd"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { onMounted, onUnmounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import axios from '@/utils/axios'
import { localGet, uploadImgServer } from '@/utils'

const router = useRouter() // 声明路由实例
const route = useRoute() // 获取路由参数
const state = reactive({
  uploadImgServer,
  token: localGet('token') || '',
  title: '',
  visible: false,
  form: {},
  loading: false,
  tableData: [], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  type: 'add', // 操作类型
})
onMounted(() => {
  getBrands()
})
onUnmounted(() => {

})
const getBrands = () => {
  state.loading = true
  axios.get('/brands', {
    params: {
      pageNumber: state.currentPage,
      pageSize: state.pageSize,
    }
  }).then(res => {
    state.tableData = res.list
    state.total = res.totalCount
    state.currentPage = res.currPage
    state.loading = false
  })
}
const changePage = (val) => {
  state.currentPage = val
  getBrands()
}
const handleBeforeUpload = (file) => {
  const sufix = file.name.split('.')[1] || ''
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
    return false
  }
}
const handleUrlSuccess = (val) => {
  state.form.brandUrl = val.url || ''
}
const submitForm = () => {
  if (state.type == 'add') {
    axios.post('/addBrand', state.form).then(res => {
      ElMessage.success('新增成功')
      getBrands()
      state.visible = false
    })
  } else {
    axios.post('/editBrand', state.form).then(res => {
      ElMessage.success('提交成功')
      getBrands()
      state.visible = false
    })
  }
}
const handleAdd = () => {
  state.type = 'add'
  state.title = '新增'
  state.form = {}
  state.visible = true
}
const handleEdit = (id) => {
  state.type = 'edit'
  state.title = '编辑'
  axios.get('/getBrandInfo/' + id).then(res => {
    state.form = res
  })
  state.visible = true
}
// 单个删除
const handleDeleteOne = (id) => {
  axios.delete('/removeBrand/' + id).then(() => {
    ElMessage.success('删除成功')
    getBrands()
  })
}
</script>

<style>
.avatar-uploader {
  width: 100px;
  height: 100px;
  color: #ddd;
  font-size: 30px;
}

.avatar-uploader-icon {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid #e9e9e9;
  padding: 32px 30px;
}
</style>